/*
 * FilePath     : \src\utils\navigation.ts
 * Author       : 苏军志
 * Date         : 2020-08-28 15:54
 * LastEditors  : 杨欣欣
 * LastEditTime : 2024-11-28 14:57
 * Description  :
 */
import common from "@/utils/common";
import logger from "@/utils/logger";

let win = window as any;

// 使用vite的import.meta.glob，用于路由懒加载
let module = import.meta.glob("@/views/**/*.vue");

const setDynamicRouters = (patentRouter: string, routerList: Array<any>, router: any) => {
  routerList.forEach((dynamicRouter: any) => {
    // 将component转换为懒加载模块
    dynamicRouter.component = module[dynamicRouter.component];
    router.addRoute(patentRouter, dynamicRouter);
    if (dynamicRouter.children?.length) {
      setDynamicRouters(dynamicRouter.name, dynamicRouter.children, router);
    }
  });
};

let registerRouteFresh = ref(true);
export default {
  set: (router: any) => {
    //导航守卫
    router.beforeEach((to: any, from: any, next: any) => {
      const session = common.session("session");
      // 设置动态路由
      if (registerRouteFresh.value && session.routerList?.length) {
        setDynamicRouters("mainLayout", session.routerList, router);
        registerRouteFresh.value = false;
        if (to.name === "404" || to.name == "developing") {
          next({ path: to.path, query: to.query });
        } else {
          next({ ...to, replace: true });
        }
        return;
      }
      //切换页面前把上页面未完成的API请求全部取消
      if (win.apiRequestList?.length > 0) {
        win.apiRequestList.forEach((request: any) => {
          if (!request.excludeCancelTypes?.includes("switch")) {
            request.cancel("switch||" + decodeURIComponent(request.key));
          }
        });
        win.apiRequestList = [];
      }

      if (!["/login", "/externalTransfer"].includes(to.path)) {
        // 切换页面前先提交当前页面日志
        logger.commitServer();
      }
      logger.setLogger({
        title: "切换页面",
        content: `fromPage: ${from.path}，toPage: ${to.path}`
      });

      // 如果要跳转的画面是需要缓存的，需要处理下
      if (to.meta.keepAlive) {
        // 如果不是从其子画面跳转过来的，则需要刷新该缓存画面
        if (from.meta.parentPath !== to.path) {
          to.meta.refreshFlag = true;
        } else {
          to.meta.refreshFlag = false;
        }
      }

      // 不需要验证则直接跳转
      if (!to.meta.auth) {
        next();
        return;
      }
      // 如果需要验证则判断token
      if (to.path === "/login" || !to.matched.some((item: any) => item.meta.auth)) {
        next();
        return;
      }
      // 对路由进行验证
      if (session?.isLogin) {
        next();
        return;
      }
      let query: any = { url: to.fullPath };
      if (to.query.token) {
        query.token = to.query.token;
      }
      // 未登录则跳转到登陆界面
      next({
        path: "/login",
        query
      });
    });
  }
};
